<template>
  <div class="box">
    <header class="header">
      <!-- 个人中心头部区域 -->
      <div class="myheader">
        <!-- 头像显示区域 -->
        <div class="HeadPortrait">
          <div class="HP_Left" @click="$router.push('/my_Personal')">
            <van-image round fit="cover" lazy-load width=".65rem" height=".65rem" :src=userimage />
            <span>{{username}}</span>
          </div>
          <div class="HP_Right" @click="showPopup">
            <img src="../../lib/img/my/打卡@2x.png" alt="" style="width:.16rem;" v-if="!PunchTheClock">
            {{ PunchTheClock ? '已打卡' : '未打卡'}}
          </div>
          <!-- 点击弹出得模态框内容 -->
          <van-popup v-model="show" style="width:2.2rem;height:2.5rem;">
            <div class="PopupTop">
              <div class="img"></div>
            </div>
            <div class="PopupBottom">
              <p class="Success">打卡成功</p>
              <van-row>
                <van-col span="8">
                  <p>{{ClockedDays}}</p>
                  <p>已连续打卡</p>
                </van-col>
                <van-col span="8">
                  <p>{{TotalNumberOfDays}}</p>
                  <p>记账总天数</p>
                </van-col>
                <van-col span="8">
                  <p>{{TotalNumberOfBookkeeping}}</p>
                  <p>记账总笔数</p>
                </van-col>
              </van-row>
            </div>
          </van-popup>
        </div>
        <!-- 连续打卡啦记账啦啥的 -->
        <div class="Record">
          <div>
            <p>{{ClockedDays}}</p>
            <p>已连续打卡</p>
          </div>
          <div>
            <p>{{TotalNumberOfDays}}</p>
            <p>记账总天数</p>
          </div>
          <div>
            <p>{{TotalNumberOfBookkeeping}}</p>
            <p>记账总笔数</p>
          </div>
        </div>
      </div>
    </header>
    <!-- 个人中心内容区域 -->
    <div class="content" id="content">
      <div class="TotalIncludes">
        <!-- 消息、记账提醒、等 -->
        <div class="news">
          <van-grid :border="false" :column-num="5">
            <van-grid-item  @click="$router.push('/my_news')">
              <van-image :src="require('../../lib/img/my/xiaoxi@2x.png')" />
              <span text>消息</span>
            </van-grid-item>
            <van-grid-item @click="$router.push('/my_Timed_Reminder')" >
              <van-image :src="require('../../lib/img/my/jizhangtixing@2x.png')" />
              <span text>记账提醒</span>
            </van-grid-item>
            <!-- <van-grid-item @click="$router.push('/my_SavingPlan')"> -->
            <van-grid-item @click="$router.push('/ComingSoon')">
              <van-image :src="require('../../lib/img/my/cunqianjihua@2x.png')" />
              <span text>存钱计划</span>
            </van-grid-item>
            <van-grid-item @click="$router.push('/my_InviteFriends')">
              <van-image :src="require('../../lib/img/my/yaoqinghaoyou@2x.png')" />
              <span text>邀请好友</span>
            </van-grid-item>
            <van-grid-item @click="$router.push('/my_SetUp')">
              <van-image :src="require('../../lib/img/my/shezhi@2x.png')" />
              <span text>设置</span>
            </van-grid-item>
          </van-grid>
        </div>
        <!-- 账单 -->
        <div class="bill" @click="$router.push('/my_bill')">
          <p class="billheader">
            <span>
              账单
            </span>
            <span>
              <van-icon name="arrow" />
            </span>
          </p>
          <van-row>
            <van-col span="6">
              <span style="font-size:.3rem;color:#282828;" v-if="month < 9">
                0{{month}}
              </span>
              <span style="font-size:.3rem;color:#282828;" v-else>
                {{month}}
              </span>
              <span style="font-size:.2rem;">
                月
              </span>
            </van-col>
            <van-col span="18">
              <van-row type="flex" justify="space-around" style="margin:0;text-align:center;">
                <van-col span="7">
                  <p class="title">收入</p>
                  <p class="num">{{Totalincome}}</p>
                </van-col>
                <van-col span="7">
                  <p class="title">支出</p>
                  <p class="num">{{Totalexpenditure}}</p>
                </van-col>
                <van-col span="7">
                  <p class="title">结余</p>
                  <p class="num">{{TotalBalance}}</p>
                </van-col>
              </van-row>
            </van-col>
          </van-row>
        </div>
        <!-- 总预算 -->
        <!-- <div class="budget" @click="$router.push('/my_budget')"> -->
        <div class="budget" @click="$router.push('/ComingSoon')">
          <p class="title">
            <span>
              <span>{{month}}</span>月总预算
            </span>
            <span>
              查看全部 <van-icon name="arrow" />
            </span>
          </p>
          <div class="BudgetContent">
            <van-row>
              <van-col span="8">
                <span v-if="ProgressTitle === 2" class="surplus">
                  剩余
                </span>
                <span v-if="ProgressTitle === 0" class="NotSet">
                  未设置
                </span>
                <span v-if="ProgressTitle === 3" class="Overspending">
                  已超支
                </span>
                <!-- rate: 圆环进度,后期data动态绑定 -->
                <van-circle v-model="currentRate" :rate=BudgetShare :speed="100" :text="text" stroke-width="120" size=".80rem" layer-color="#eaeaea" color="#fdd949" style="margin-top: .05rem;"/>
              </van-col>
              <van-col span="16" >
                <p>
                  <span>
                    剩余预算:
                  </span>
                  <span>
                    {{RemainingBudget}}.00
                  </span>
                </p>
                <p>
                  <span>
                    本月预算:
                  </span>
                  <span>
                    {{BudgetOfThisMonth}}.00
                  </span>
                </p>
                <p>
                  <span>
                    本月支付:
                  </span>
                  <span>
                    {{PaymentThisMonth}}.00
                  </span>
                </p>
              </van-col>
            </van-row>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 直接导入axios请求其他接口数据
import axios from 'axios'
// 导入请求数据函数
import { usermyinfo, BillingData, userbudget } from '@/api'
// 安装好vue的ui库后在这里引入模块, 使用vant ui库组件三部曲引入vue 引入组件 使用组件
import Vue from 'vue'
import { Image as VanImage, Lazyload, Grid, GridItem, Col, Row, Circle, Popup, Icon } from 'vant'
Vue.use(VanImage)
Vue.use(Lazyload)
Vue.use(Grid)
Vue.use(GridItem)
Vue.use(Col)
Vue.use(Row)
Vue.use(Circle)
Vue.use(Popup)
Vue.use(Icon)
export default {
  // 设置data初始值
  data () {
    return {
      id: 0, // 用户id
      username: '', // 用户名
      userimage: 'https://s1.ax1x.com/2020/05/06/YVUCQA.png', // 用户头像
      PunchTheClock: true, // 是否打卡
      show: false, // 签到弹出层
      ClockedDays: 0, // 已连续打卡天数
      TotalNumberOfDays: 0, // 记账总天数
      // income: 1000, // 收入
      // expenditure: 2600, // 支出
      // balance: 0, // 结余 ===> 结余等于收入减去支出
      TotalNumberOfBookkeeping: 0, // 记账总笔数
      RemainingBudget: 0, // 剩余预算 ===> 剩余预算 = 本月预算 - 本月支付
      BudgetOfThisMonth: 0, // 本月预算
      PaymentThisMonth: 0, // 本月支付,需要后端数据
      currentRate: 0, // 圆形总进度条当前值
      BudgetShare: 0, // 剩余预算占总预算的占比 = 剩余预算 / 本月预算 ===> 1 以内的小数,可以继续下一步的计算一类的转换为100为基准的
      month: '', // 当前月份
      ProgressTitle: 0, // 控制圆形进度条中显示的标题, 0: 未设置, 1: 正常显示进度, 2: 已超支
      BillList: [], // 账单列表
      Totalincome: 0, // 总支出
      Totalexpenditure: 0, // 总收入
      TotalBalance: 0 // 总结余,根据各个月份的结余计算出来的
    }
  },
  computed: {
    text () {
      // 圆形进度条
      if (this.ProgressTitle === 2) {
        return this.currentRate.toFixed(0) + '%'
      } else {
        return ''
      }
    }
  },
  // 注册组件
  components: {},
  // 生命周期钩子函数
  mounted () {
    // 获取id值
    this.id = localStorage.getItem('lazypiguserid')
    // 结余 = 收入 - 支出
    // this.balance = this.income - this.expenditure
    // 剩余预算 = 本月预算 - 本月支付
    // this.RemainingBudget = this.BudgetOfThisMonth - this.PaymentThisMonth
    // 当前月份
    // const date = new Date()
    // this.month = date.getMonth() + 1
    // 剩余预算占总预算的占比 = 剩余预算 / 总预算
    // this.BudgetShare = Math.round((this.RemainingBudget / this.BudgetOfThisMonth) * 100)
    // 获取用户个人信息
    usermyinfo().then((res) => {
      // console.log(res)
      if (res.data.code === 200) { // 请求成功
        this.username = res.data.data.head[0].username
        // this.userimage = res.data.data.head[0].title_image
        // this.ClockedDays = res.data.data.clock_day
        // this.TotalNumberOfDays = res.data.data.sum_day
        // this.TotalNumberOfBookkeeping = res.data.data.sum_account
      }
    })
    // id请求成功以后,进行头像得获取,post传参使用data: {},get传参使用共params: {}
    axios({
      method: 'post',
      url: 'http://60.205.153.211:3000/api/lazypig/obtainlazypigavatar',
      data: {
        userid: Number(this.id)
      }
    }).then((res) => {
      // console.log('1111', res)
      this.userimage = res.data.data
    })
    // 调用请求打卡记录的函数
    this.GetClockInRecord()
    // 请求当前月份账单数据
    BillingData().then((res) => {
      // console.log(res)
      this.month = res.data.data.month
      // this.expenditure = res.data.data.disburse_money // 总支出
      // this.income = res.data.data.income_money // 总收入
      // this.balance = res.data.data.surplus // 结余
    })
    // 获取用户预算数据
    userbudget().then((res) => {
      // console.log(res.data.data[0])
      this.BudgetOfThisMonth = res.data.data[0].budget // 本月预算
      this.PaymentThisMonth = res.data.data[0].disburse // 本月支付
      // 剩余预算 = 本月预算 - 本月支付
      this.RemainingBudget = this.BudgetOfThisMonth - this.PaymentThisMonth
      // 先判断一下
      // 判断,若是本月预算为0,则为未设置预算 状态为0; 若是本月支付大于本月预算且本月预算不为0,则为已超支 状态为3; 若是其他情况则为正常显示 状态为2
      if (this.BudgetOfThisMonth === 0) { // 未设置
        this.ProgressTitle = 0 // 状态
        this.RemainingBudget = 0 // 剩余预算
        this.PaymentThisMonth = 0 // 本月支付
      } else if (this.PaymentThisMonth > this.BudgetOfThisMonth && this.BudgetOfThisMonth !== 0) { // 已超支
        this.ProgressTitle = 3
      } else { // 正常
        this.ProgressTitle = 2
        // 剩余预算占总预算的占比 = 剩余预算 / 总预算
        this.BudgetShare = Math.round((this.RemainingBudget / this.BudgetOfThisMonth) * 100)
      }
    })
    // 请求账单数据
    axios({
      method: 'post',
      url: 'http://60.205.153.211:3000/api/lazyBookkeeping/QueryBookkeeping',
      data: {
        userid: localStorage.getItem('lazypiguserid')
      }
    }).then((res) => {
      // console.log(res.data.data)
      this.TotalNumberOfBookkeeping = res.data.data.length
      // 年
      this.year = res.data.data[0].timer.split('/')[0] * 1
      // 月
      this.month = res.data.data[0].timer.split('/')[1] * 1
      // 获取出来以后根据时间来进行划分
      // 双层循环,对其中每个元素都进行比较分类
      const temporarylist = [] // 存放临时数据
      res.data.data.map((item, index) => {
        // 每一次内层循环结束后都是分好一次类别的数,所以需要将账单收支总计以及每一个时间下的账单详细清零重计
        let TotalRevenue = 0 // 收入总计
        let TotalExpenditure = 0 // 支出总计
        const detailedlist = [] // 存放相应的同一时间下的对象类型的账单
        res.data.data.map((itm, idx) => {
          // 判断外层循环中的timer是否与内层是否相等然后进行分类统计
          if (item.timer === itm.timer) {
            // 支出收入计算
            if (itm.bill * 1 > 0) {
              TotalRevenue += itm.bill * 1
              // console.log('收入', TotalRevenue)
            } else {
              TotalExpenditure += itm.bill * 1
              // console.log('支出', TotalRevenue)
            }
            // 编译账单详情
            const objbill = {
              url: itm.icon, // 图标
              remarks: itm.remark, // 备注
              money: itm.bill * 1// 账单
            }
            // console.log('money', objbill.money)
            // 然后放进数组中
            detailedlist.push(objbill)
            // console.log('detailedlist', detailedlist)
            // 而后在继续编译时间分类下的账单详情
            const obj = {
              day: itm.timer.split('/')[2] * 1, // 从时间例如2020/05/20中取出最后一个代表天的数,然后可以用用这个对数组进行去重还有排序的操作
              time: itm.timer,
              income: TotalRevenue, // 收入
              expenditure: TotalExpenditure, // 支出
              MonthlyBalance: TotalRevenue * 1 + TotalExpenditure * 1, // 每月结余
              detailedlist
            }
            // 最后完成之后编译进临时总数组中
            temporarylist.push(obj)
            // this.BillList.push(obj)
          }
        })
      })
      // console.log('temporarylist', temporarylist)
      // 我们通过观察最后结果发现会有很多数据不完整的重复元素,我们可以通过计算纯收入与重新计算后的流水和时候相等来剔除掉不对的数据
      // let num = 0
      const arr = [] // 存放剔除错误数据的数组
      temporarylist.map((item, index) => {
        // console.log('次数', num += 1)
        let flowingWater = 0
        item.detailedlist.map((itm, index) => {
          // console.log(item.detailedlist)
          // console.log('流水', itm.money)
          flowingWater += itm.money
        })
        // console.log('数据收支和', item.income * 1 + item.expenditure * 1)
        // console.log('数据流水和', flowingWater)
        if (item.income * 1 + item.expenditure * 1 === flowingWater) {
          // console.log('数据一样则将本数据保存到总数组中')
          arr.push(item)
        }
      })
      // 数组去重
      this.BillList.push(arr[0])
      // console.log(this.BillList)
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        // for (let j = i; j < arr.length; j++) {
        //   const itm = arr[j]
        //   if (item.day === itm.day) {
        //   }
        // }
        // 判断一下在数组this.BillList中是否存在当前元素
        const isflag = this.BillList.some((itm, idx, arr) => {
          return itm.day === item.day
        })
        if (isflag === false) {
          this.BillList.push(item)
        }
      }
      // console.log(arr)
      // 总收入
      this.BillList.map((itm, idx) => {
        this.Totalincome += itm.income
      })
      // 总支出
      this.BillList.map((itm, idx) => {
        this.Totalexpenditure += itm.expenditure
      })
      // 计算总结余,扽与总收入减去总支出
      this.TotalBalance = this.Totalincome + this.Totalexpenditure
      // 记账总天数
      this.TotalNumberOfDays = this.BillList.length
    })
  },
  // 计算属性
  methods: {
    // 打卡
    PunchTheClockfn () {
      // 点击打卡获取到当前时间,然后参数请求打卡接口
      const mydate = new Date()
      const year = mydate.getFullYear()
      const month = mydate.getMonth() + 1
      const day = mydate.getDate()
      // console.log(year, month, day)
      axios({
        method: 'get',
        url: 'http://60.205.153.211:3000/api/lazypigCock',
        params: {
          userid: this.id,
          year: year,
          month: month,
          day: day
        }
      }).then((res) => {
        // 点击按钮完成之后重新请求打卡记录接口,重新渲染
        this.GetClockInRecord()
      })
    },
    // 弹出框(模态框)
    showPopup () {
      this.show = true
      // 掏出模态框顺便调用打卡函数
      this.PunchTheClockfn()
    },
    // 封装一个请求打卡记录的函数
    GetClockInRecord () {
      // 获取到当前时间
      const mydate = new Date()
      const year = mydate.getFullYear()
      const month = mydate.getMonth() + 1
      const day = mydate.getDate()
      axios({
        method: 'get',
        url: 'http://60.205.153.211:3000/api/lazypigCock/GetClockInRecord',
        params: {
          userid: Number(this.id)
        }
      }).then((res) => {
        // console.log('获取到打卡记录', res)
        this.ClockedDays = res.data.data[0].Totaldays
        const datayear = (res.data.data[0].year) * 1 // 隐形转换
        const dataday = (res.data.data[0].day) * 1 // 隐形转换
        const datamonth = (res.data.data[0].month) * 1 // 隐形转换
        if (year === datayear && month === datamonth && day === dataday) {
          this.PunchTheClock = true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 样式
  @import "@/lib/reset.scss";
  // 头部
  .myheader {
    @include rect(100%, 1.88rem);
    @include background-color(#FDD949);
    @include border-radius(0 0 .2rem .2rem);
    padding-top: .49rem;
    .HeadPortrait {
      height: .65rem;
      width: 3.18rem;
      margin: 0 .31rem;
      display: flex;
      justify-content: space-between;
      align-items: center;
      span {
        line-height: .65rem;
      }
      .HP_Left {
        display: flex;
        justify-content: space-between;
        span {
          margin-left: .16rem;
          font-size: .18rem;
        }
      }
      .HP_Right {
        @include rect(.65rem, .2rem);
        @include border-radius(.2rem);
        background-color: #fefefe;
        font-size: .10rem;
        text-align: center;
        line-height: .2rem;
      }
      // 弹出的模态框
      .van-popup {
        @include border-radius(.2rem);
        .PopupTop {
          height: 1.12rem;
          background-color: #fdd949;
          position: relative;
          .img {
            @include rect(1.04rem, 1.04rem);
            @include border-radius(50%);
            background-color: #f4f4f4;
            position: absolute;
            bottom: -0.20rem;
            left: 50%;
            margin-left: -0.52rem;
          }
        }
        .PopupBottom {
          height: .64rem;
          text-align: center;
          .Success {
            font-size: .135rem;
            line-height: .80rem;
          }
          .van-row {
            .van-col {
              font-size: .135rem;
              color: #b7b7b7;
            }
          }
        }
      }
    }
    // 连续打卡等
    .Record {
      height: .45rem;
      width: 3.18rem;
      line-height: .225rem;
      margin: .26rem auto;
      display: flex;
      justify-content: space-between;
      div {
        width: .80rem;
        text-align: center;
        font-size: .10rem;
        p{
          &:nth-child(1) {
            font-size: .20rem;
            font-weight: 400;
            color: #1c1c1c;
          }
          &:nth-child(2) {
            font-size: .15rem;
            color: #333333;
          }
        }
      }
    }
  }
  // 内容
  .content {
    color: black;
    .TotalIncludes{ // 直接根部设置总框以及居中
      width: 3.45rem;
      margin: .30rem auto;
      // 消息、记账提醒等
      .news {
        margin-top: .15rem;
        height: .7rem;
        border-bottom: .015rem #eeeeee solid;
        border-radius: 0 0 .04rem .04rem;
        // 加/deep/表示更改组件中的css样式
        /deep/ .van-grid-item__content {
          padding: 0;
        }
        .van-image {
          width: .30rem;
          height: .25rem;
        }
        span {
          line-height: .35rem;
          font-size: .12rem;
        }
      }
      // 账单
      .bill {
        height: 1rem;
        margin-top: .15rem;
        padding: .1rem;
        border-bottom: .015rem #eeeeee solid;
        border-radius: 0 0 .04rem .04rem;
        .billheader {
          display: flex;
          justify-content: space-between;
          span {
            &:nth-of-type(1) {
              font-size: .16rem;
              font-weight: 500;
            }
            &:nth-of-type(2) {
              color: #7C7C7C;
              font-size: .15rem;
            }
          }
        }
        .van-row {
          margin-top: .02rem;
          .van-col {
            height: .45rem;
          }
          .van-col--6 {
            border-right: .01rem #EAEAEA solid;
            text-align: center;
            line-height: .45rem;
          }
          .title {
            line-height: .25rem;
            font-size: .15rem;
            color: #a7a7a7;
          }
          .num {
            line-height: .25rem;
            font-size: .12rem;
            color: #1C1C1C;
          }
        }
      }
      // 总预算
      .budget {
        height: 1.20rem;
        padding: .1rem;
        border-bottom: .015rem #eeeeee solid;
        background-color: #fcfcfc;
        .title {
          display: flex;
          justify-content: space-between;
          line-height: .15rem;
          span {
            &:nth-of-type(1) {
              font-size: .15rem;
            }
            &:nth-of-type(2) {
              font-size: .10rem;
              color: #a5a5a5;
            }
          }
        }
        .BudgetContent {
          .van-row {
            .van-col {
              margin-top: .05rem;
              height: .74rem;
              // background-color: burlywood;
            }
            // 左边圆形进度框
            .van-col--8 {
              position: relative;
              padding-left: .12rem;
              // 标题为剩余
              .surplus {
                font-size: .10rem;
                color: #c5c5c5;
                position: absolute;
                top: 34%;
                left: 37%;
              }
              // 标题为未设置,已超支
              .NotSet, .Overspending {
                font-size: .16rem;
                color: red;
                position: absolute;
                top: 48%;
                left: 27%;
              }
              /deep/ .van-circle__text {
                top: 60%;
                font-size: .16rem;
                color: #444444;
              }
            }
            // 右侧内容
            .van-col--16 {
              p {
                display: flex;
                justify-content: space-between;
                &:nth-of-type(1) {
                  margin-bottom: .10rem;
                  font-size: .15rem;
                }
                &:nth-of-type(2), &:nth-of-type(3) {
                  font-size: .12rem;
                  color: #c5c5c5;
                  margin-bottom: .05rem;
                }
              }
            }
          }
        }
      }
    }
  }
</style>
